<?php

/**
 * Trieda reprezentujuca modul na spravu tetxoveho obsahu
 *
 */
class AdminContent extends Page {

	/**
     * Metoda na zobrazenie triedy
     *
     */
	public function show() {
		global $db, $r;

		parent::show();



		if(!$this->checkAccess("editor")) rLocate(); //ak uzivatel nema dostatocne prava`

		//id obsahu
		$id   = $r["arg"][3] + 0;


		$this->path[] = array(
		"admin/content",
		i18n::t("contents")
		); //path


		$this->tpl->assign("path", $this->path);

		/**
        * Jednotlive akcie s obsahom
        */

		/**
         * Zmazanie stranky s obsahom
         *
         * Ak sa v URL vyskytuje del-link alebo del-page
         */
		if ((in_array($r["arg"][2], array("del-link", "del-page"))) && ($id)) {

			$this->delete($id);
		}

		/**
         * Posunutie stranky s obsahom v ramci menu
         *
         * Ak sa v URL vyskyzuje up alebo down
         */

		if (in_array($r["arg"][2], array("up", "down"))) {

			$this->moveItem($id);
		}

		/**
         * Moľné odkazy pre TinyMCE
         *
         * Ak sa v URL vyskytuje link-list
         */
		if ($r["arg"][2]=="link-list") {

			$this->adminLinkList();
			return;
		}



		/**
         * Samotne spracovanie textovej stranky
         */


		/**
         * Nastavenie stranky ako titulnej
         *
         * Ak je v URL default-page
         */

		if (($r["arg"][2] == "default-page") && ($id)) {


			$this->setDefault($id);
		}


		/**
         * Editacia a vytvorenie novej stranky - spradcovanie a zobrazenie formulara
         *
         * Ak je v URL edit-page alebo add-page
         */

		if (in_array($r["arg"][2], array("edit-page", "add-page"))) {


			/**
             * Zmena obsahu stranky alebo pridanie novej stranky - spracovanie
             *
             */

			if (($_POST["action"] == "change") || ($_POST["action"] == "add")) {




				// overenie vstupu
				foreach (array("title", "menu", "text") as $a) { // pre vsetky atributy
					if (!get_magic_quotes_gpc()) {
						$_POST[$a] =addslashes($_POST[$a]); // osetrenie vstupu
					}
					$_POST[$a] = trim($_POST[$a]); // odstranenie nadbytocnych medzier
				}

				// $error - pole chyb
				if ($_POST["title"] == "") {
				$error["sk"][] = i18n::t("c_title") ;
				}

				if ($_POST["text"] == "") {  // nebol zadany text
				$error["sk"][] = i18n::t("c_text") ;
				}

				$alias = $db->getCell("SELECT id FROM content WHERE alias='{$_POST["alias"]}'");

				if ($_POST["action"] == "add") {
					if ($alias) {
						$error["sk"][] = i18n::t("c_alias");
					}
				}

				// ak nastali chyby vo vstupe
				if ($error) {


					$content = $_POST; // obsah z formulara
					$posted = true; // odoslane

					$this->tpl->assign("content",$content);

					//rPrint($content);

					$this->tpl->assign("error", array(
					i18n::t("c_please") . " ".implode(", ", $error["sk"]) . "."
					)); // oznamenie o chybe
					//return;
					$this->editPageForm($posted,$id);
					//$this->tpl->display("admin-content-page.tpl");
					//return;

					//ak nenastali ziadne chyby
				} else {

					// ak ide o editaciu nie nove pridanie

					if ($_POST["action"] == "change") {

						$this->editPage($id);
						return;


						/**
                     * Pridavanie novej stranky
                     */

					} elseif ($_POST["action"] == "add") {

						$this->addPage();
						return;

					} // pridavanie koniec


				}

				//return;
			}


			/**
             * Zobrazenie pridavacieho/editacneho formulara
             */

			// ak ide o pridanie novej stranky - v URL add-page
			if ($r["arg"][2] == "add-page") {

				$content = $this->addPageForm($posted);

				// ak ide o editaciu existujucej stranky - v URL edit-page
			} elseif ($r["arg"][2] == "edit-page") {

				$content = $this->editPageForm($posted,$id);
			}

			if (!empty($_POST))
				$content = $_POST;


			// moznosti menu

			$tree = new rTree("menu", "id", "parent_id"); // strom nenu
			$menu_tree = array();

			foreach ($this->menu_positions as $position => $info) { // pre vsetky menu - bocne a hlavne

				//vytvorenie menu stromu
                $tree->setQuery("tree", "
                    SELECT t1.%ID%, t1.title, t1.link, COUNT(t2.%ID%) AS count
                    FROM %TABLE% t1
                    LEFT JOIN %TABLE% t2
                       ON t2.%PARENT_ID% = t1.%ID%
                      AND t2.lang = '{$r["lang"]}'
                    WHERE t1.%PARENT_ID% = %d
                      AND t1.menu = '$position'
                      AND t1.lang = '{$r["lang"]}'
                    GROUP BY t1.%ID%, t1.weight, t1.title, t1.link
                    ORDER BY t1.weight, t1.%ID%
                ");

                $menu = $tree->getSimpleTree(0, 0, true); //stavba stromu


				foreach ($menu as &$item) {
					$item["depth"]++;
					$title = $item["title"];
					$item["title"] = array(
					"admin" => true,
					$r["admin_lang"] => $title
					);
				} // spracovanie poloziek

				// pridanie bocneho a hlavneho menu
				array_unshift($menu, array(
				"id"    => $position,
				"title" => array(
				"admin"         => true,
				$r["admin_lang"] => rStrCase($this->menu_positions[$position][$r["admin_lang"]], false)
				),
				"depth" => 0
				));
				$menu_tree = array_merge($menu_tree, $menu);
			}


			// pridanie polozky Nepridavat
			if ($r["arg"][2] == "add-page") {

				array_unshift($menu_tree, array(
				"id"    => "no-add",
				"title" => array(
				"admin" => true,
				"sk"    => "-- nepridávať --",
				"en"    => "-- do not add --"
				),
				"depth" => 0
				));

				/**
             * Moznosti menu pri editacii
             *
             * v URL je edit-page
             */
			} elseif ($r["arg"][2] == "edit-page") {

				// polozka v menu
				$menu_item = $db->getRow("
                    SELECT * FROM menu
                    WHERE link = 'content/$id'
                ");

				if ($menu_item) { // ak sa stranka nachadza ako polozka v menu

					for ($i = 0; $i < count($menu_tree); $i++) { //zmazanie polozky menu

						if ($menu_tree[$i]["id"] == $menu_item["id"]) {

							$depth = $menu_tree[$i]["depth"];
							unset($menu_tree[$i]);
							$i++;

							while ($menu_tree[$i]["depth"] > $depth) { //a jej podpoloziek
								unset($menu_tree[$i]);
								$i++;
							}

							break;
						}

					}
				} // stranka ako polozka menu

				// polozka Nepirdavat
				array_unshift($menu_tree, array(
				"id"    => "remove",
				"title" => array(
				"admin" => true,
				"sk"    => "-- odstrániť z menu / nepridávať --",
				"en"    => "-- remove from menu - do not add --"
				),
				"depth" => 0
				));
			}
			$this->tpl->assign("menu_tree", $menu_tree); //menu na sablonu

			$this->tpl->assign("content", $content); // obsah na sablonu

			$this->tpl->display("admin-content-page.tpl"); // zobrazenie
			return;
		}



		/**
         * Editacia odkazu
         */


		/**
         * Pridanie a editacia odkazu
         *
         * v URL add-link alebo edit-link
         */

		if (in_array($r["arg"][2], array("add-link", "edit-link"))) {

			// spracovanie a nie zobrazenie formulara

			if (($_POST["action"] == "change") || ($_POST["action"] == "add")) {


				// skontrolovanie formulara

				foreach (array("title") as $a) {
					if (!get_magic_quotes_gpc()) {
						$_POST[$a] =addslashes($_POST[$a]); // osetrenie vstupu
					}
					$_POST[$a] = trim($_POST[$a]); // odstranenie prebytocnych bielych znakov
				}

				if ($_POST["title"] == "") {
				$error["sk"][] = i18n::t("c_title");
				}

				if ($_POST["link"] == "") {
				$error["sk"][] = i18n::t("c_url");
				}



				// ak sa vyskytli chyby vo formulari
				if ($error) {
					$this->tpl->assign("error", array(
					i18n::t("c_please") . " ".implode(", ", $error["sk"]) . "."
					));

					$content = $_POST; // obsah z formulara
					$posted = true; // formular odoslany


					// aks a nevyskytli ziadne chyby
				} else {

					// upravenie odkazu

					if ($_POST["action"] == "change") {

						$this->editLink($id);


						// vlozenie odkazu nie uprava

					} elseif ($_POST["action"] == "add") {

						$this->addLink();
					}

					rLocate("admin/content"); //presmerovanie na spravu obsahu
					return;

				}
			}


			/**
             * Zobrazenie formulara
             */

			//  formular na pridavanie
			if ($r["arg"][2] == "add-link") {
				$this->path[] = array(
				"",
				i18n::t("content_newlink")
				);
				$content["add"] = true;

				//ak ide o zobrazenie po prvy raz
				if (!$posted) {

					//predvolene menu
					$content["parent_id"] = "side";
				}

				// formular pre editaciu
			} elseif ($r["arg"][2] == "edit-link") {

				$content = $this->editLinkForm($id,$posted);
			}


			$tree = new rTree("menu", "id", "parent_id"); //strom menu
			$menu_tree = array();

			foreach ($this->menu_positions as $position => $info) {

				$tree->setQuery("tree", "
                    SELECT t1.%ID%, t1.title, t1.link, COUNT(t2.%ID%) AS count
                    FROM %TABLE% t1
                    LEFT JOIN %TABLE% t2
                       ON t2.%PARENT_ID% = t1.%ID%
                      AND t2.lang = '{$r["lang"]}'
                    WHERE t1.%PARENT_ID% = %d
                      AND t1.menu = '$position'
                      AND t1.lang = '{$r["lang"]}'
                    GROUP BY t1.%ID%, t1.weight, t1.title, t1.link
                    ORDER BY t1.weight, t1.%ID%
                "); // vygenerovanie poloziek

				$menu = $tree->getSimpleTree(0, 0, true); //vytvorenie menu s polozkami

				foreach ($menu as &$item) {
					$item["depth"]++;
					$title = $item["title"];
					$item["title"] = array(
					"admin" => true,
					$r["admin_lang"] => $item["title"]
					);
				}

				// pridanie volby hlavneho a bocneho menu
				array_unshift($menu, array(
				"id"    => $position,
				"title" => array(
				"admin"         => true,
				$r["admin_lang"] => rStrCase($this->menu_positions[$position][$r["admin_lang"]], false)
				),
				"depth" => 0
				));


				$menu_tree = array_merge($menu_tree, $menu);
			}

			// odobratie podloloziek odkazu z menu
			if ($r["arg"][2] == "edit-link") {

				$menu_item = $content;

				if ($menu_item) {
					for ($i = 0; $i < count($menu_tree); $i++) {
						if ($menu_tree[$i]["id"] == $menu_item["id"]) { // odobratie polozky
							$depth = $menu_tree[$i]["depth"];
							unset($menu_tree[$i]);
							$i++;
							while ($menu_tree[$i]["depth"] > $depth) { //a jej podoloziek
								unset($menu_tree[$i]);
								$i++;
							}
							break;
						}
					}
				}
			}
			$this->tpl->assign("menu_tree", $menu_tree); //menu na sablonu


			$this->tpl->assign("content", $content); //obsah

			$this->tpl->display("admin-content-link.tpl"); //zobrazenie
			return;
		}


		/**
         * Predvolena akcia - zobrazenie obsahu
         */

		$tree = new rTree("menu", "id", "parent_id"); //strom menu

		$pages_in_menu = array();

		foreach ($this->menu_positions as $position => $info) { // pre vsetky menu

			$tree->setQuery("tree", "
                SELECT t1.%ID%, t1.title, t1.link, COUNT(t2.%ID%) AS count, c.\"default\", c.id AS content_id
                FROM %TABLE% t1
                LEFT JOIN %TABLE% t2
                   ON t2.%PARENT_ID% = t1.%ID%
                  AND t2.menu = '$position'
                  AND t2.lang = '{$r["lang"]}'
                LEFT JOIN content c
                   ON t1.link = 'content/' || c.id
                WHERE t1.%PARENT_ID% = %d
                  AND t1.menu = '$position'
                  AND t1.lang = '{$r["lang"]}'
                GROUP BY t1.%ID%, t1.weight, t1.title, t1.link, c.\"default\", c.id
                ORDER BY t1.weight, t1.%ID%
            ");

			$p = $tree->getSimpleTree(0, 0, true); // vsetky stranky, ktore su v menu

			for ($i = 0; $i < count($p); $i++) {

				if ($p[$i]["content_id"])
				$pages_in_menu[] = $p[$i]["content_id"]; // stranka v menu

				$p[$i]["default"] = $p[$i]["default"] == "t"; //predvolena stranka

				// umoznenie posunutia v menu nahor a nadol
				/*if ($i!=0)*/ $p[$i]["up"] = true;
				/*if ($i!=count($p)-1)*/ $p[$i]["down"] = true;

				// stranka s obsahom nie odkaz
				if (eregi("content/[0-9]+", $p[$i]["link"])) {
					$p[$i]["content_id"] = eregi_replace("content/([0-9]+)", "\\1", $p[$i]["link"]);
					$p[$i]["type"] = "page";
				} else { // odkaz
					$p[$i]["content_id"] = $p[$i]["id"];
					$p[$i]["type"] = "link";
				}
			}
			$pages[$position] = $p;
		}

		$where = "";
		if ($pages_in_menu) {
			$where = "AND NOT id IN (" . implode(",", $pages_in_menu) . ")"; //aby neboli v menu
		}

		$pages["unassigned"] = $db->getArrRow("
            SELECT * FROM content
            WHERE lang = '{$r["lang"]}' $where
            ORDER BY id
        ");// stranky ktre nie su v menu

		foreach ($pages["unassigned"] as &$p) { //spracovanie stranok a odkazov, ktore ne su v menu
			$p["content_id"] = $p["id"];
			$p["default"] = $p["default"] == "t";
			$p["depth"] = 0;
			$p["type"] = "page";
		}

		$pages_positions = $this->menu_positions; // oznacenie nezaradenych stranok
		$pages_positions["unassigned"] = array(
		"admin" => true,
		"sk"    => "Nezaradené stránky",
		"cz"    => "Nezařazené stránky",
		"en"	=> "Unassigned pages"
		);

		$this->tpl->assign("pages_positions", $pages_positions); // rozne menu

		$this->tpl->assign("pages", $pages); // polozky
		$this->tpl->display("admin-content-list.tpl"); //zobrazenie
		return;

	}


	/**
     * Metoda na odobratie polozky z menu
     *
     * @param integer $id identifikator polozky, ktora sa ma odstranit
     */
	static public function removeMenu($id) {
		global $db, $r;

		$item = $db->getRow("
            SELECT * FROM menu
            WHERE id = $id AND lang = '{$r["lang"]}'
        "); // najdenie polozky v menu

		$weight = $item["weight"]; // vaha polozky

		// susedne polozky s vyssou vahou
		$syblings = $db->getArrRow("
            SELECT * FROM menu
            WHERE parent_id = {$item["parent_id"]}
              AND weight > $weight
              AND menu = '{$item["menu"]}'
              AND lang = '{$r["lang"]}'
            ORDER BY weight
        ");

		// podpolozky
		$children = $db->getArrRow("
            SELECT * FROM menu
            WHERE parent_id = $id AND lang = '{$r["lang"]}'
            ORDER BY weight
        ");

		$query = "";

		// umiestenie podpoloziek danej polozky do menu rodica
		foreach ($children as $child) {
			$query .= "
                UPDATE menu SET
                    parent_id   = {$item["parent_id"]},
                    weight      = $weight
                WHERE id = {$child["id"]};
            ";
			$weight++;
		}

		// posunutie susednych poloziek nizsie
		foreach ($syblings as $sybling) {
			$query .= "
                UPDATE menu SET
                    weight      = $weight
                WHERE id = {$sybling["id"]};
            ";
			$weight++;
		}
		$db->query($query);

		// konecne vymazanie polozky z menu
		$db->query("
            DELETE FROM menu
            WHERE id = $id
        ");
	}

	/**
     * Metoda na zmazanie stranky alebo linky
     *
     * @param integer $id id spracovavanej stranky alebo linky
     */
	private function delete($id) {
		global $db,$r;

		$type = ereg_replace('del-', "", $r["arg"][2]); // zistenie typu - ci ide o stranku alebo dokaz

		if ($type == "link") { //ak ide o linku
			$this->removeMenu($id); // len zmazanie linky z menu

		} elseif ($type == "page") { // ak ide o stranku
			$item = $db->getRow("
                    SELECT * FROM menu WHERE link = 'content/$id'
                "); // zistenie ci je v menu

			if ($item) //ak je stranka v menu
			self::removeMenu($item["id"]); // odstranenie z menu

			$db->query("
                    DELETE FROM content WHERE id = $id
                "); // odstranenie stranky
		}

		rLocate("admin/content"); // presmerovanie spat na spravu obsahu
		return;
	}

	/**
     * Metoda na zmenu pozicie polozky v menu
     *
     * @param integer $id id posuvanej polozky
     */
	private function moveItem($id) {
		global $db,$r;

		$item = $db->getRow("
                SELECT * FROM menu WHERE id = $id
            "); // udaje z menu o stranke

		$syblings = $db->getArrRow("
                SELECT * FROM menu
                WHERE parent_id = '{$item["parent_id"]}' AND menu = '{$item["menu"]}' AND lang='{$r[lang]}'
                ORDER BY weight
            "); // ziskanie poloziek v menu na rovnakej urovni

		if (count($syblings) > 1) { // ak ma surodencov (polozky na rovnakej urovni)
			$id2 = 0; // polozka s ktorou sa dana polozka vymeni

			// najdenie danej polozky medzi polozkami v danej urovni menu
			for ($i = 0; $i < count($syblings); $i++) {
				if ($syblings[$i]["id"] == $id)
				break;
			}

			if (($r["arg"][2] == "up") && ($i > 0)) { //ak ide o posunutie hore a polozka sa ma kam posunut
				$id2 = $syblings[$i-1]["id"]; // predchadzajuca polozka
			}

			if (($r["arg"][2] == "down") && ($i < count($syblings)-1)) { // ak ide o posunutie dole a polozka sa ma kam posunut
				$id2 = $syblings[$i+1]["id"]; // nasledujuca polozka
			}

			if ($id2) {
				$weight2 = $db->getCell("
                        SELECT weight FROM menu WHERE id = $id2
                    ") + 0; // vaha polozky, s ktorou bude dana polzoka vymenena

				$db->query("
                        UPDATE menu SET weight = $weight2           WHERE id = $id;
                        UPDATE menu SET weight = {$item["weight"]}  WHERE id = $id2;
                    "); // vymena vah poloziek
			}

		}

		rLocate("admin/content"); // presmerovanie spat na spravu stranok
		return;
	}

	/**
     * Metoda na pripravu udajov pe formular na editovanie stranky
     *
     * @param boolean $posted priznak, ci uz bol formular odoslany
     * @return array pripravene data
     */
	private function addPageForm($posted) {
		global $r,$db;

		$this->path[] = array(
		"",
		i18n::t("content_newpage")
		); // path

		$content["add"] = true; // ide o novu stranku

		// ak je formular zobrazeny prvykrat
		if (!$posted) {

			// predvolene menu
			$content["menu_id"] = "side";

			// predvoleny jazyk
			$content["lang"] = $r["lang"];
		}

		$this->tpl->assign("path", $this->path);
		$this->tpl->assign("albums", $db->getArrRow("SELECT id,title FROM gallery_albums WHERE lang='{$r["lang"]}'"));

		return $content;
	}

	/**
     * Metoda na pripravu udajov pre formular na editaciu straky
     *
     * @param boolean $posted priznak ci uz bol formular poslany
     * @param integer $id id editovanej stranky
     * @return array pripravene data
     */
	private function editPageForm($posted,$id) {
		global $r,$db;

		// ak je formular zobrazeny prvykrat, predvyplnia sa udaje z DB
		if (!$posted) {
			$content = $db->getRow("
                        SELECT * FROM content
                        WHERE id = $id AND lang = '{$r["lang"]}'
                    "); //obsah
    	} else
    		$content = $_POST;

			// najde polozku v menu, ktorej stranka patri
			if ($content) {

				$menu = $db->getRow("
                            SELECT * FROM menu
                            WHERE link = 'content/$id' AND lang = '{$r["lang"]}'
                        "); // polozky menu

				// ak neexsituje, nevytvori sa
				if (!$menu) {
					$content["menu"] = "";
					$content["menu_id"] = "remove";

					//ak exsituje, najde a oznaci sa
				} else {
					$content["menu"] = $menu["title"];
					if ($menu["parent_id"] == 0) {
						$content["menu_id"] = $menu["menu"];
					} else {
						$content["menu_id"] = $menu["parent_id"] + 0;
					}
				}
			}

		if (!$content) { // chyba
			$this->path[] = array(
			"",
			i18n::t("not_found")
			);
			$this->status(
			i18n::t("not_found"),
			i18n::t("msg_access3")
			);

			$this->tpl->assign("path", $this->path);

			return;
		}

		$content["language"] = $r["i18n"]["languages"][$content["lang"]]; //jazyk

		// path
		$this->path[] = array(
		"content/$id",
		$r["lang"] => $content["title"]
		);
		$this->path[] = array(
		"",
		i18n::t("content_edit")
		);

		$this->tpl->assign("albums", $db->getArrRow("SELECT id,title FROM gallery_albums WHERE lang='{$r["lang"]}'"));

		$this->tpl->assign("path", $this->path);

		$search = array("/\&lt;/","/\&gt;/");
    $replace= array(htmlspecialchars("&lt;"),htmlspecialchars("&gt;"));
    $content[text] = preg_replace($search, $replace, $content[text]);

		return $content;
	}

	/**
     * Metoda na pridanie pozadovanej polozky do menu
     *
     * @param integer $id id polozky
     */
	private function addToMenu($id) {
		global $db,$r;

		// naplnenie poloziek a menu
		if (in_array($_POST["menu_id"], array_keys($this->menu_positions))) {
			$parent = 0;
			$menu = $_POST["menu_id"];
		} else {
			$parent = $_POST["menu_id"] + 0;
			$menu = $db->getCell("
                                    SELECT menu FROM menu
                                    WHERE id = $parent
                                ");
		}

		$menu_id = $db->getCell("
                                SELECT NEXTVAL('menu_id_seq')
                            "); // nasledujuce ID

		$weight = $db->getCell("
                                SELECT MAX(weight) FROM menu
                                WHERE parent_id = $parent AND menu = '$menu'
                            ") + 1; // vaha pre novu polozku v menu

		$title = $_POST["menu"] ? $_POST["menu"] : $_POST["title"]; // nazov

		// pridanie do menu pre kazdy jazyk
		$query = "";
		//foreach ($r["i18n"]["languages"] as $lang => $languages) {
			$query .= "
                                    INSERT INTO menu (id, parent_id, weight, menu, lang, title, link)
                                    VALUES (
                                        $menu_id,
                                        $parent,
                                        $weight,
                                        '$menu',
                                        '{$_POST["lang"]}',
                                        '$title',
                                        'content/$id'
                                    );
                                ";
		//}
		$db->query($query);
	}

	/**
     * Metoda na nastavenie predvolenej (uvodnej) stranky
     *
     * @param integer $id id stranky
     */
	private function setDefault($id) {
		global $db, $r;

		$db->query("
                 UPDATE content SET \"default\" = false WHERE lang='{$r["lang"]}';
                UPDATE content SET \"default\" = true WHERE id = $id AND lang='{$r["lang"]}';
            "); // nastavenie default-page na TRUE pre danu stranku

		rLocate("admin/content");  // presmerovanie spat na spravu stranok
		return;
	}

	/**
     * Metoda na zmenu obshau editovanej stranky
     *
     * @param integer $id id spracovavanej linky
     */
	private function editPage($id) {
		global $db,$r;
//die('x');
		// najprv sa edituje menu

		$old_item = $db->getRow("
                            SELECT * FROM menu
                            WHERE link = 'content/$id'
                        "); // polozka v menu

		// zmzazanie z menu
		if (($old_item) && ($_POST["menu_id"] == "remove")) {
			$this->removeMenu($old_item["id"]);

			// zmena polozky v menu
		} else {

			// naplnenie poloziek a menu
			if (in_array($_POST["menu_id"], array_keys($this->menu_positions))) {
				$parent = 0;
				$menu = $_POST["menu_id"];
			} else {
				$parent = $_POST["menu_id"] + 0;
				$menu = $db->getCell("
                                    SELECT menu FROM menu
                                    WHERE id = $parent
                                ");
			}
			$title = $_POST["menu"] ? $_POST["menu"] : $_POST["title"];

			// zmena nazvu polozky v menu
			if ($old_item["title"] != $title) {
				$db->query("
                                    UPDATE menu SET title = '$title'
                                    WHERE id = {$old_item["id"]} AND lang = '{$r["lang"]}'
                                ");
			}

			// zmena pozicie polozky v menu
			if (($old_item["parent_id"] != $parent) || ($old_item["menu"] != $menu)) {

				$weight = $db->getCell("
                                    SELECT MAX(weight) FROM menu
                                    WHERE parent_id = $parent AND menu = '$menu'
                                ") + 1; //max vaha v menu + 1

				// pridanie na koniec
				if ($old_item) {
					$db->query("
                                        UPDATE menu SET
                                            parent_id   = $parent,
                                            menu        = '$menu',
                                            weight      = $weight
                                        WHERE id = {$old_item["id"]}
                                    ");

					// ak polozka v menu neeistovala, je pridana
				} else {
					$menu_id = $db->getCell("
                                        SELECT NEXTVAL('menu_id_seq')
                                    "); // nasledujuce ID

					$query = "";
					//foreach ($r["i18n"]["languages"] as $lang => $languages) {
						$query .= "
                                            INSERT INTO menu (id, parent_id, weight, menu, lang, title, link)
                                            VALUES (
                                                $menu_id,
                                                $parent,
                                                $weight,
                                                '$menu',
                                                '{$r["lang"]}',
                                                '$title',
                                                'content/$id'
                                            );
                                        ";
					//} // pridanie do menu pre kazdy jazyk
					$db->query($query);
				}
			} // zmena pozicie v menu dokoncena

		} // zmena menu dokoncena


		/**
                         * Zmena obsahu
        */

        if ($_POST["alias"]=="") // zmazanie aliasu
			$alias = $id;
		else
			$alias = $_POST["alias"];

		if (trim($_POST["album_id"])=="")
				$_POST["album_id"]="NULL";

		$db->query("
                            UPDATE content
                            SET title       = '{$_POST["title"]}',
                                text        = '{$_POST["text"]}',
								alias       = '$alias',
								album_id	=  {$_POST["album_id"]}
                            WHERE id = $id AND lang = '{$r["lang"]}'
                        ");



		rLocate("content/$alias"); //presmerovanie na pridanu/editovanu stranku
		return;

	}

	/**
     * Metoda na pridanie stranky
     *
     */
	private function addPage() {
		global $db,$r;



		$id = $db->getCell("
                            SELECT NEXTVAL('content_id_seq')
                        "); //nove id

		//osetrenie aliasu
		if ($_POST["alias"]=="")
			$alias = $id;
		else
			$alias = $_POST["alias"];

		if (trim($_POST["album_id"])=="")
				$_POST["album_id"]="NULL";

		// vlozenie pre kazdy jazyk
		$query = "";
		//foreach ($r["i18n"]["languages"] as $lang => $language) {
			$text = $_POST["text"];

			$query .= "
                                INSERT INTO content (
                                    id, lang, title, text, alias, \"default\", album_id
                                ) VALUES (
                                    $id,
                                    '{$r["lang"]}',
                                    '{$_POST["title"]}',
                                    '$text',
									'$alias',
                                    false,
									 {$_POST["album_id"]}
                                );
                            ";
		//}
		$db->query($query);
		//die();

		/**
                         * Pridanie novej stranky do menu (ak ma byt pridana)
                         */
		if ($_POST["menu_id"] != "no-add") {

			$this->addToMenu($id);
		}

		rLocate("content/$alias"); //presmerovanie na pridanu/editovanu stranku
		return;
	}

	private function editLink($id) {
		global $db,$r;

		// povodny odkaz
		$old_item = $db->getRow("
                            SELECT * FROM menu
                            WHERE id = $id
                        ");

		// naplnenie menu
		if (in_array($_POST["menu_id"], array_keys($this->menu_positions))) {
			$parent = 0;
			$menu = $_POST["menu_id"];
		} else {
			$parent = $_POST["menu_id"] + 0;
			$menu = $db->getCell("
                                SELECT menu FROM menu
                                WHERE id = $parent
                            ");
		}

		// uprava odkazu
		$db->query("
                            UPDATE menu SET
                                title = '{$_POST["title"]}',
                                link  = '{$_POST["link"]}'
                            WHERE id = $id AND lang = '{$r["lang"]}'
                        ");

		// zmena pozicie odkazu v menu
		if (($old_item["parent_id"] != $parent) || ($old_item["menu"] != $menu)) {

			$weight = $db->getCell("
                                SELECT MAX(weight) FROM menu
                                WHERE parent_id = $parent AND menu = '$menu'
                            ") + 1; // nova vaha

			// pridanie odkazu na koniec danej polozky menu
			if ($old_item) {
				$db->query("
                                    UPDATE menu SET
                                        parent_id   = $parent,
                                        menu        = '$menu',
                                        weight      = $weight
                                    WHERE id = $id
                                ");

			}
		} // zmena pozicie odkazu v menu
	}

	/**
     * Metoda na pridanie linky
     *
     */
	private function addLink() {
		global $db,$r;

		if (in_array($_POST["menu_id"], array_keys($this->menu_positions))) { //menu
			$parent = 0;
			$menu = $_POST["menu_id"];
		} else {
			$parent = $_POST["menu_id"] + 0;
			$menu = $db->getCell("
                                SELECT menu FROM menu
                                WHERE id = $parent
                            ");
		}

		$menu_id = $db->getCell("
                            SELECT NEXTVAL('menu_id_seq')
                        "); //nove id

		$weight = $db->getCell("
                            SELECT MAX(weight) FROM menu
                            WHERE parent_id = $parent AND menu = '$menu'
                        ") + 1; //nova vaha

		$query = "";
		foreach ($r["i18n"]["languages"] as $lang => $languages) { // pridanie do menu pre kazdy jazyk
			$query .= "
                                INSERT INTO menu (id, parent_id, weight, menu, lang, title, link, target)
                                VALUES (
                                    $menu_id,
                                    $parent,
                                    $weight,
                                    '$menu',
                                    '$lang',
                                    '{$_POST["title"]}',
                                    '{$_POST["link"]}',
                                    '{$_POST["target"]}'
                                );
                            ";
		}
		$db->query($query); //zapis do DB
	}

	/**
     * Metoda na pripravu dat pre formular na editaciu linky
     *
     * @param integer $id id spracovavanej linky
     * @param boolean $posted priznak, ci bol formular uz odoslany
     * @return array pripravene data
     */
	private function editLinkForm($id,$posted) {
		global $db,$r;

		//ak ide o zobrazenie po prvy raz
		if (!$posted) {
			$content = $db->getRow("
                        SELECT * FROM menu
                        WHERE id = $id AND lang = '{$r["lang"]}'
                    "); // spravny obsha z DB

			// najdenie polozky menu, kde odkaz patri
			if ($content) {
				$menu = $db->getRow("
                            SELECT * FROM menu
                            WHERE link = 'content/$id' AND lang = '{$r["lang"]}'
                        ");

				//ak sa nenachadza v menu, odobrat
				if (!$menu) {
					$content["menu"] = "";
					$content["menu_id"] = "remove";

					// ak sa nachadza v menu, najdenie polozky
				} else {
					$content["menu"] = $menu["title"];
					if ($menu["parent_id"] == 0) {
						$content["menu_id"] = $menu["menu"];
					} else {
						$content["menu_id"] = $menu["parent_id"] + 0;
					}
				}
			}
		}

		if (!$content) { //aj neexistuje obsah
			rLocate("admin/content"); // presmerovanie na spravu obsahu
			return;
		}

		$content["language"] = $r["i18n"]["languages"][$content["lang"]]; //jazyk

		// path
		$this->path[] = array(
		"content/$id",
		$r["lang"] => $content["title"]
		);
		$this->path[] = array(
		"",
		i18n::t("content_edit")
		);

		$this->tpl->assign("path", $this->path);

		return $content;
	}

	/**
	 * Medóta na vygenerovanie moľných odkazov pre TinyMCE
	 */
	private function adminLinkList() {
        global $db, $r;

        $data = $db->getArrRow("SELECT id,title,alias FROM content ORDER BY title");

        $list=array();

        foreach ($data as $item)
        	$list[] = "['{$item[title]} (/content/{$item[alias]})', '/content/{$item[alias]}']";

        echo("var tinyMCELinkList = new Array(\n" . implode(",\n", $list) . "\n);");
        return;

    }

}

?>